import { ajax, decode, getAjaxBaseURL } from '@jecloud/utils';
import { useGlobalStore } from '@common/store/global-store';
const API_RBAC_LOGIN_THIRD_TEMPCODE = '/je/rbac/cloud/login/thirdTempCode';
/**
 * 三方登录根据临时码获得登录信息
 * @param {String} tempCode 临时码，一分钟失效
 * @returns
 */
export function loadThirdTempCodeApi(tempCode) {
  return ajax({ url: API_RBAC_LOGIN_THIRD_TEMPCODE, params: { tempCode } }).then((data) => {
    if (data.success) {
      const config = decode(data.data);
      if (config.url) {
        config.url = config.url.split('#')[1] || config.url;
      }
      config.depts = config.info;
      return config;
    } else {
      return Promise.reject(data);
    }
  });
}
/**
 * 三方登录守卫
 * @param {*} param0
 */
export function thirdRouterGuard(to, from, next) {
  const globalStore = useGlobalStore();
  const { tempCode } = to.query;
  delete to.query.tempCode;
  // 三方登录，临时授权码
  loadThirdTempCodeApi(tempCode)
    .then((data) => {
      if (data.select) {
        next({
          name: 'ThirdLogin',
          params: { ...to.params, tempCode },
          query: to.query,
        });
      } else {
        globalStore.setToken(data.token);
        next(to);
      }
    })
    .catch(() => {
      next();
    });
}
/**
 * 三方登录
 * @param {*} query
 * @returns
 */
export function isThirdLogin(query = {}) {
  return !!query.tempCode;
}
/**
 * 获取原图片文件
 * @param {*} fileKey
 * @param {*} thumbnail
 * @returns
 */
export function getLoginImageUrl(fileKey, thumbnail = false) {
  const globalStore = useGlobalStore();
  const method = thumbnail ? 'getThumbnailPicture' : 'getOriginalPicture';
  const plan = globalStore.activePlan;
  return `${getAjaxBaseURL()}/je/document/open/${method}/${plan}/${fileKey}`;
}

/**
 * 检查token，如果有可用的，更新token
 * @returns
 */
export function checkThirdToken() {
  return ajax({ url: '/je/rbac/cloud/token/validAndCheck', method: 'GET', token: false })
    .then(({ success, data }) => {
      if (success) {
        // 更新token
        data && useGlobalStore().setToken(data);
      }
    })
    .catch((err) => {
      console.error(err);
    });
}
